"""
PPT Generator FastAPI Application
Main application entry point with CORS, middleware, and basic routing structure.
"""

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.responses import JSONResponse
import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Create FastAPI application
app = FastAPI(
    title="PPT Generator API",
    description="AI-powered PowerPoint presentation generator using LangChain and DeepSeek",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

# CORS configuration
CORS_ORIGINS = os.getenv("CORS_ORIGINS", "http://localhost:3000,http://localhost:5173").split(",")

app.add_middleware(
    CORSMiddleware,
    allow_origins=CORS_ORIGINS,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allow_headers=["*"],
)

# Trusted host middleware for security
app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=["localhost", "127.0.0.1", "*.localhost"]
)

# Health check endpoint
@app.get("/health")
async def health_check():
    """Health check endpoint to verify API is running"""
    return {
        "status": "healthy",
        "message": "PPT Generator API is running",
        "version": "1.0.0"
    }

# Root endpoint
@app.get("/")
async def root():
    """Root endpoint with API information"""
    return {
        "message": "PPT Generator API",
        "version": "1.0.0",
        "docs": "/docs",
        "health": "/health"
    }

# Include API routes
from app.api.websocket import router as websocket_router
from app.api.ai import router as ai_router
from app.api.template import router as template_router
from app.services.connection_monitor import connection_monitor

app.include_router(websocket_router, prefix="/api", tags=["websocket"])
app.include_router(ai_router, prefix="/api", tags=["ai"])
app.include_router(template_router, prefix="/api", tags=["template"])

# Application lifecycle events
@app.on_event("startup")
async def startup_event():
    """Application startup event handler"""
    # Start connection monitoring
    await connection_monitor.start_monitoring()

@app.on_event("shutdown")
async def shutdown_event():
    """Application shutdown event handler"""
    # Stop connection monitoring
    await connection_monitor.stop_monitoring()

# API route group placeholder
@app.get("/api")
async def api_info():
    """API information endpoint"""
    return {
        "message": "PPT Generator API endpoints",
        "available_endpoints": [
            "/api/generate-ppt",
            "/api/preview/{session_id}",
            "/api/download/{session_id}",
            "/api/ws/{session_id}",
            "/api/ws/status",
            "/api/ai/status",
            "/api/ai/test-connection",
            "/api/ai/generate-outline",
            "/api/ai/generate-detailed-outline",
            "/api/ai/generate-slide",
            "/api/ai/generate-visual-suggestions",
            "/api/ai/optimize-content",
            "/api/templates",
            "/api/templates/{template_id}",
            "/api/templates/apply",
            "/api/templates/categories"
        ]
    }

# Global exception handler
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
    """Global exception handler for unhandled errors"""
    return JSONResponse(
        status_code=500,
        content={
            "error": "Internal server error",
            "message": "An unexpected error occurred",
            "detail": str(exc) if os.getenv("DEBUG", "false").lower() == "true" else None
        }
    )

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_level="info"
    )